package com.small.nacos.config.server.utils;

import com.alibaba.nacos.common.executor.ExecutorFactory;
import com.alibaba.nacos.common.executor.NameThreadFactory;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class ConfigExecutor {

    private static final String Config_NAME = "com.small.nacos.config";

    private static final ScheduledExecutorService LONG_POLLING_EXECUTOR = ExecutorFactory.Managed
            .newSingleScheduledExecutorService(Config_NAME,
                    new NameThreadFactory("com.small.nacos.config.LongPolling"));

    private static final ScheduledExecutorService TIMER_EXECUTOR = ExecutorFactory.Managed
            .newScheduledExecutorService(Config_NAME, 10,
                    new NameThreadFactory("com.small.nacos.config.server.timer"));

    /**
     * 处理异步通知（配置更新）
     */
    private static final ScheduledExecutorService ASYNC_NOTIFY_EXECUTOR = ExecutorFactory.Managed
            .newScheduledExecutorService(Config_NAME, 100,
                    new NameThreadFactory("com.small.nacos.config.AsyncNotifyService"));

    public static void executeLongPolling(Runnable runnable) {
        LONG_POLLING_EXECUTOR.execute(runnable);
    }

    public static ScheduledFuture<?> scheduleLongPolling(Runnable runnable, long period, TimeUnit unit) {
        return LONG_POLLING_EXECUTOR.schedule(runnable, period, unit);
    }

    public static void scheduleConfigTask(Runnable command, long initialDelay, long delay, TimeUnit unit) {
        TIMER_EXECUTOR.scheduleWithFixedDelay(command, initialDelay, delay, unit);
    }

    public static void executeAsyncNotify(Runnable runnable) {
        ASYNC_NOTIFY_EXECUTOR.execute(runnable);
    }

    public static void scheduleAsyncNotify(Runnable command, long delay, TimeUnit unit) {
        ASYNC_NOTIFY_EXECUTOR.schedule(command, delay, unit);
    }
}
